/*
 * Copyright 2005-2013 biz-united. All rights reserved.
 * Support: http://www.biz-united.com.cn
 * License: http://www.biz-united.com.cn/?page_id=5&act=3
 */
package net.biz.controller.shop.member;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.biz.Message;
import net.biz.Pageable;
import net.biz.Setting;
import net.biz.controller.shop.BaseController;
import net.biz.entity.Area;
import net.biz.entity.Cart;
import net.biz.entity.CartItem;
import net.biz.entity.Coupon;
import net.biz.entity.CouponCode;
import net.biz.entity.Member;
import net.biz.entity.Order;
import net.biz.entity.Order.OrderStatus;
import net.biz.entity.Order.PaymentStatus;
import net.biz.entity.PaymentMethod;
import net.biz.entity.Receiver;
import net.biz.entity.Shipping;
import net.biz.entity.ShippingMethod;
import net.biz.plugin.PaymentPlugin;
import net.biz.service.AreaService;
import net.biz.service.CartService;
import net.biz.service.CouponCodeService;
import net.biz.service.MemberService;
import net.biz.service.OrderService;
import net.biz.service.PaymentMethodService;
import net.biz.service.PluginService;
import net.biz.service.ReceiverService;
import net.biz.service.ShippingMethodService;
import net.biz.service.ShippingService;
import net.biz.util.JsonUtils;
import net.biz.util.ParamsUtil;
import net.biz.util.SettingUtils;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.home766.dto.AreaDto;
import com.home766.dto.PaymentDTO;
import com.home766.entity.Invoice;
import com.home766.entity.Shops;
import com.home766.service.ShopsService;
import com.home766.util.DateTime;
import com.home766.util.PaymentUtil;
import com.home766.util.StringUtil;

/**
 * Controller - 会员中心 - 订单
 * 
 * @author BIZ Team
 * @version 3.0
 */
@Controller("shopMemberOrderController")
@RequestMapping("/member/order")
public class OrderController extends BaseController {

	/** 每页记录数 */
	private static final int PAGE_SIZE = 10;

	@Resource(name = "memberServiceImpl")
	private MemberService memberService;
	@Resource(name = "areaServiceImpl")
	private AreaService areaService;
	@Resource(name = "receiverServiceImpl")
	private ReceiverService receiverService;
	@Resource(name = "cartServiceImpl")
	private CartService cartService;
	@Resource(name = "paymentMethodServiceImpl")
	private PaymentMethodService paymentMethodService;
	@Resource(name = "shippingMethodServiceImpl")
	private ShippingMethodService shippingMethodService;
	@Resource(name = "couponCodeServiceImpl")
	private CouponCodeService couponCodeService;
	@Resource(name = "orderServiceImpl")
	private OrderService orderService;
	@Resource(name = "shippingServiceImpl")
	private ShippingService shippingService;
	@Resource(name = "pluginServiceImpl")
	private PluginService pluginService;
	@Resource(name="shopsServiceImpl")
	private ShopsService shopsService;

	/**
	 * 保存收货地址
	 */
	@RequestMapping(value = "/save_receiver", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> saveReceiver(Receiver receiver, Long areaId) {
		Map<String, Object> data = new HashMap<String, Object>();
		receiver.setArea(areaService.find(areaId));
		if (!isValid(receiver)) {
			data.put("message", ERROR_MESSAGE);
			return data;
		}
		Member member = memberService.getCurrent();
		if (Receiver.MAX_RECEIVER_COUNT != null && member.getReceivers().size() >= Receiver.MAX_RECEIVER_COUNT) {
			data.put("message", Message.error("shop.order.addReceiverCountNotAllowed", Receiver.MAX_RECEIVER_COUNT));
			return data;
		}
		receiver.setMember(member);
		if(null!=receiver.getId() || !"".equals(receiver.getId().toString())){
			receiverService.update(receiver);
		}else{
			receiverService.save(receiver);
		}
		receiver.setAreaName(receiver.getArea().getFullName());
		data.put("message", SUCCESS_MESSAGE);
		data.put("receiver", receiver);
		return data;
	}

	/**
	 * 订单锁定
	 */
	@RequestMapping(value = "/lock", method = RequestMethod.POST)
	public @ResponseBody
	boolean lock(String sn) {
		Order order = orderService.findBySn(sn);
		if (order != null && memberService.getCurrent().equals(order.getMember()) && !order.isExpired() && !order.isLocked(null) && order.getPaymentMethod() != null && order.getPaymentMethod().getMethod() == PaymentMethod.Method.online && (order.getPaymentStatus() == PaymentStatus.unpaid || order.getPaymentStatus() == PaymentStatus.partialPayment)) {
			order.setLockExpire(DateUtils.addSeconds(new Date(), 20));
			order.setOperator(null);
			orderService.update(order);
			return true;
		}
		return false;
	}

	/**
	 * 检查支付
	 */
	@RequestMapping(value = "/check_payment", method = RequestMethod.POST)
	public @ResponseBody
	boolean checkPayment(String sn) {
		Order order = orderService.findBySn(sn);
		if(order.getOrderType()==ParamsUtil.CART_TYPE_SCHEME){
			if(order != null && memberService.getCurrent().equals(order.getMember()) && order.getSchemePaymentStatus() == ParamsUtil.SCHEME_PAYMENT_STATUS_PAID){
				return true;
			}
		}else{
			if (order != null && memberService.getCurrent().equals(order.getMember()) && order.getPaymentStatus() == PaymentStatus.paid) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 优惠券信息
	 */
	@RequestMapping(value = "/coupon_info", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> couponInfo(String code) {
		Map<String, Object> data = new HashMap<String, Object>();
		Cart cart = cartService.getCurrent();
		if (cart == null || cart.isEmpty()) {
			data.put("message", Message.warn("shop.order.cartNotEmpty"));
			return data;
		}
		if (!cart.isCouponAllowed()) {
			data.put("message", Message.warn("shop.order.couponNotAllowed"));
			return data;
		}
		CouponCode couponCode = couponCodeService.findByCode(code);
		if (couponCode != null && couponCode.getCoupon() != null) {
			Coupon coupon = couponCode.getCoupon();
			if (!coupon.getIsEnabled()) {
				data.put("message", Message.warn("shop.order.couponDisabled"));
				return data;
			}
			if (!coupon.hasBegun()) {
				data.put("message", Message.warn("shop.order.couponNotBegin"));
				return data;
			}
			if (coupon.hasExpired()) {
				data.put("message", Message.warn("shop.order.couponHasExpired"));
				return data;
			}
			if (!cart.isValid(coupon)) {
				data.put("message", Message.warn("shop.order.couponInvalid"));
				return data;
			}
			if (couponCode.getIsUsed()) {
				data.put("message", Message.warn("shop.order.couponCodeUsed"));
				return data;
			}
			data.put("message", SUCCESS_MESSAGE);
			data.put("couponName", coupon.getName());
			return data;
		} else {
			data.put("message", Message.warn("shop.order.couponCodeNotExist"));
			return data;
		}
	}

	/**
	 * 信息
	 */
	@RequestMapping(value = "/info", method = RequestMethod.GET)
	public String info(ModelMap model) {
		Cart cart = cartService.getCurrent();
		Integer cartType=null;
		if (cart == null || cart.isEmpty()) {
			return "redirect:/cart/list.jhtml";
		}
		Set<CartItem> set=cart.getCartItems();
		if(null!=set&&!set.isEmpty()){
			for(CartItem ci:set){
				if(ci.getIsSubmit()){
					if(cartType==null){
						cartType=ci.getCartType();
					}
					if(cartType!=ci.getCartType()){
						return "redirect:/cart/list.jhtml";
					}
				}
			}
		}
		if (!isValid(cart)) {
			return ERROR_VIEW;
		}
		Order order = orderService.build(cart, null, null, null, null, false, null, false, null);
		model.addAttribute("order", order);
		model.addAttribute("cartToken", cart.getToken());
		model.addAttribute("paymentMethods", paymentMethodService.findAll());
		model.addAttribute("shippingMethods", shippingMethodService.findAll());
		model.addAttribute("orderType", cartType);
		model.addAttribute("areas", areaService.findRoots());
		return "/shop/member/order/info";
	}
	
	@RequestMapping(value="/buildScheme",method=RequestMethod.POST)
	public String buildScheme(Integer orderType,Long schemeId,Long[] ids,Integer schemeArea, ModelMap model,
			@RequestParam(defaultValue = "false") Boolean isTemperature,
			@RequestParam(defaultValue = "false") Boolean isDissipate,
			@RequestParam(defaultValue = "false") Boolean isPromote,
			@RequestParam(defaultValue = "false") Boolean isController,
			String jsonParam){
		if(!StringUtil.isNullOrSpace(jsonParam)){
			jsonParam = StringUtil.jsonString(jsonParam);
		}
		Order order = orderService.build(getCurrent(), null, null, null, null, false, null, false, null,ParamsUtil.CART_TYPE_SCHEME,schemeId,ids,schemeArea, isDissipate, isTemperature, isPromote, isController,jsonParam);
		model.addAttribute("order", order);
		model.addAttribute("paymentMethods", paymentMethodService.findAll());
		model.addAttribute("shippingMethods", shippingMethodService.findAll());
		model.addAttribute("orderType", ParamsUtil.CART_TYPE_SCHEME);
		model.addAttribute("areas", areaService.findRoots());
		Cart cart=cartService.getCurrent();
		String token=null;
		if(cart!=null){
			cart.getToken();
		}
		jsonParam=jsonParam.replace("\"", "'");
		model.addAttribute("cartToken", token);
		model.addAttribute("schemeId", schemeId);
		model.addAttribute("jsonParam", jsonParam);
		model.addAttribute("schemeArea", schemeArea);
		model.addAttribute("isTemperature", isTemperature);
		model.addAttribute("isDissipate", isDissipate);
		model.addAttribute("isPromote", isPromote);
		model.addAttribute("isController", isController);
		
		return "/shop/member/order/info";
	}

	/**
	 * 计算
	 */
	@RequestMapping(value = "/calculate", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> calculate(Long paymentMethodId, Long shippingMethodId, String code, @RequestParam(defaultValue = "false") Boolean isInvoice, 
			String invoiceTitle, @RequestParam(defaultValue = "false") Boolean useBalance, String memo,Integer orderType,Long schemeId,Long[] ids,Integer schemeArea,
			@RequestParam(defaultValue = "false") Boolean isTemperature,
			@RequestParam(defaultValue = "false") Boolean isDissipate,
			@RequestParam(defaultValue = "false") Boolean isPromote,
			@RequestParam(defaultValue = "false") Boolean isController,
			String jsonParam) {
		Map<String, Object> data = new HashMap<String, Object>();
		Cart cart = null;
		if(orderType!=ParamsUtil.CART_TYPE_SCHEME){
			cart = cartService.getCurrent();
			if (cart == null || cart.isEmpty()) {
				data.put("message", Message.error("shop.order.cartNotEmpty"));
				return data;
			}
		}
		PaymentMethod paymentMethod = paymentMethodService.find(paymentMethodId);
		ShippingMethod shippingMethod = shippingMethodService.find(shippingMethodId);
		CouponCode couponCode = couponCodeService.findByCode(code);
		Order order=null;
		if(orderType==ParamsUtil.CART_TYPE_NORMAL){
			order = orderService.build(cart, null, paymentMethod, shippingMethod, couponCode, isInvoice, invoiceTitle, useBalance, memo);
		}else{
			jsonParam=jsonParam.replace("'", "\"");
			order = orderService.build(getCurrent(), null, null, null, null, false, null, false, null,ParamsUtil.CART_TYPE_SCHEME,schemeId,ids,schemeArea, isDissipate, isTemperature, isPromote, isController,jsonParam);
		}
		data.put("message", SUCCESS_MESSAGE);
		data.put("quantity", order.getQuantity());
		data.put("price", order.getPrice());
		data.put("freight", order.getFreight());
		data.put("promotionDiscount", order.getPromotionDiscount());
		data.put("couponDiscount", order.getCouponDiscount());
		data.put("tax", order.getTax());
		data.put("amountPayable", order.getAmountPayable());
		
		if(orderType==ParamsUtil.CART_TYPE_SCHEME){
			data.put("schemeId", schemeId);
			data.put("schemeArea", schemeArea);
			data.put("isTemperature", isTemperature);
			data.put("isDissipate", isDissipate);
			data.put("isPromote", isPromote);
			data.put("isController", isController);
		}
		
		return data;
	}

	/**
	 * 创建
	 */
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public @ResponseBody
 Message create(Long shopId, Integer orderType,
			String cartToken, Long receiverId, Long paymentMethodId,Long shippingMethodId, String code,
			@RequestParam(defaultValue = "false") Boolean isInvoice,String invoiceTitle,
			@RequestParam(defaultValue = "false") Boolean useBalance,String memo, 
			Long schemeId, Long[] ids, Integer schemeArea,Integer invoiceType,
			String organizationName,String registrationCode,String registerAddress,String registerPhone,
			String bankOfDeposit,String bankAccount,String consignee,String phone,String address) {
		Cart cart = cartService.getCurrent();
		if(orderType!=ParamsUtil.CART_TYPE_SCHEME){
			if (cart == null || cart.isEmpty()) {
				return Message.warn("shop.order.cartNotEmpty");
			}
			if (!StringUtils.equals(cart.getToken(), cartToken)) {
				return Message.warn("shop.order.cartHasChanged");
			}
			if (cart.getIsLowStock()) {
				return Message.warn("shop.order.cartLowStock");
			}
		}
		
		Receiver receiver = receiverService.find(receiverId);
		if (receiver == null) {
			return Message.error("shop.order.receiverNotExsit");
		}
		PaymentMethod paymentMethod = paymentMethodService.find(paymentMethodId);
		if (paymentMethod == null) {
			return Message.error("shop.order.paymentMethodNotExsit");
		}
		ShippingMethod shippingMethod = shippingMethodService.find(shippingMethodId);
		if (shippingMethod == null) {
			return Message.error("shop.order.shippingMethodNotExsit");
		}
		if (!paymentMethod.getShippingMethods().contains(shippingMethod)) {
			return Message.error("shop.order.deliveryUnsupported");
		}
		CouponCode couponCode = couponCodeService.findByCode(code);
		if(orderType==ParamsUtil.CART_TYPE_NORMAL){
			Set<CartItem> set=cart.getCartItems();
			for(CartItem ci:set){
				if(ci.getIsSubmit()){
					orderType=ci.getCartType();
					break;
				}
			}
		}
		//如果需要发票
		Invoice invoice = null;
		if(isInvoice){
			if(invoiceType == null){
				return Message.warn("请选择发票类型！");
			}
			if(invoiceType == ParamsUtil.ORDER_INVOICE_TYPE_NORMAL){
				//普通发票
				if(StringUtil.isNullOrSpace(invoiceTitle)){
					return Message.warn("发票抬头为空！");
				}
			}else {
				//专用发票
				if(StringUtil.isNullOrSpace(organizationName)){
					return Message.warn("发票单位名称为空！");
				}
				if(StringUtil.isNullOrSpace(registrationCode)){
					return Message.warn("发票纳税人识别码为空！");
				}
				if(StringUtil.isNullOrSpace(registerAddress)){
					return Message.warn("发票注册地址为空！");
				}
				if(StringUtil.isNullOrSpace(registerPhone)){
					return Message.warn("发票注册电话为空！");
				}
				if(StringUtil.isNullOrSpace(bankOfDeposit)){
					return Message.warn("发票开户银行为空！");
				}
				if(StringUtil.isNullOrSpace(bankAccount)){
					return Message.warn("发票银行账户为空！");
				}
				if(StringUtil.isNullOrSpace(consignee)){
					return Message.warn("发票收票人姓名为空！");
				}
				if(StringUtil.isNullOrSpace(phone)){
					return Message.warn("发票收票人电话为空！");
				}
				if(StringUtil.isNullOrSpace(address)){
					return Message.warn("发票收票人地址为空！");
				}
				invoice = new Invoice();
				invoice.setOrganizationName(organizationName);
				invoice.setRegistrationCode(registrationCode);
				invoice.setRegisterAddress(registerAddress);
				invoice.setRegisterPhone(registerPhone);
				invoice.setBankAccount(bankAccount);
				invoice.setBankOfDeposit(bankOfDeposit);
				invoice.setConsignee(consignee);
				invoice.setPhone(phone);
				invoice.setAddress(address);
			}
		}
		if(isInvoice && invoiceType == ParamsUtil.ORDER_INVOICE_TYPE_INCREMENT && invoice == null){
			return Message.warn("增值税发票信息填写不完整！");
		}
		Order order = orderService.create(shopId,orderType,cart, receiver, paymentMethod, shippingMethod, couponCode, isInvoice, invoiceTitle, useBalance, memo, null,schemeId,ids,schemeArea,invoice,invoiceType,null,null,null,null,null);
		return Message.success(order.getSn());
	}
	/**
	 * @param isDissipate 是否选中散热器 
	 * @param isTemperature 是否选中温控面板
	 * @param isPromote 是否选中提升泵
	 * @param isController 是否选中控制器
	 * 
	 * @param jsonParam json字符串
	 * 创建
	 */
	@RequestMapping(value = "/createScheme", method = RequestMethod.POST)
	public @ResponseBody
 Message createScheme(Long shopId, Integer orderType,
			String cartToken, Long receiverId, Long paymentMethodId,Long shippingMethodId, String code,
			@RequestParam(defaultValue = "false") Boolean isInvoice,String invoiceTitle,
			@RequestParam(defaultValue = "false") Boolean useBalance,String memo,
			@RequestParam(defaultValue = "false") Boolean isTemperature,
			@RequestParam(defaultValue = "false") Boolean isDissipate,
			@RequestParam(defaultValue = "false") Boolean isPromote,
			@RequestParam(defaultValue = "false") Boolean isController,
			String jsonParam,
			Long schemeId, Long[] ids, Integer schemeArea,Integer invoiceType,
			String organizationName,String registrationCode,String registerAddress,String registerPhone,
			String bankOfDeposit,String bankAccount,String consignee,String phone,String address) {
		
		if(StringUtil.isNullOrSpace(jsonParam)){
			return Message.warn("参数错误,请稍后再试");
		}
		jsonParam=jsonParam.replace("'", "\"");
		Cart cart = cartService.getCurrent();
		if(orderType!=ParamsUtil.CART_TYPE_SCHEME){
			if (cart == null || cart.isEmpty()) {
				return Message.warn("shop.order.cartNotEmpty");
			}
			if (!StringUtils.equals(cart.getToken(), cartToken)) {
				return Message.warn("shop.order.cartHasChanged");
			}
			if (cart.getIsLowStock()) {
				return Message.warn("shop.order.cartLowStock");
			}
		}
		Receiver receiver = receiverService.find(receiverId);
		if (receiver == null) {
			return Message.error("shop.order.receiverNotExsit");
		}
		PaymentMethod paymentMethod = paymentMethodService.find(paymentMethodId);
		if (paymentMethod == null) {
			return Message.error("shop.order.paymentMethodNotExsit");
		}
		ShippingMethod shippingMethod = shippingMethodService.find(shippingMethodId);
		if (shippingMethod == null) {
			return Message.error("shop.order.shippingMethodNotExsit");
		}
		if (!paymentMethod.getShippingMethods().contains(shippingMethod)) {
			return Message.error("shop.order.deliveryUnsupported");
		}
		CouponCode couponCode = couponCodeService.findByCode(code);
		if(orderType==ParamsUtil.CART_TYPE_NORMAL){
			Set<CartItem> set=cart.getCartItems();
			for(CartItem ci:set){
				if(ci.getIsSubmit()){
					orderType=ci.getCartType();
					break;
				}
			}
		}
		//如果需要发票
		Invoice invoice = null;
		if(isInvoice){
			if(invoiceType == null){
				return Message.warn("请选择发票类型！");
			}
			if(invoiceType == ParamsUtil.ORDER_INVOICE_TYPE_NORMAL){
				//普通发票
				if(StringUtil.isNullOrSpace(invoiceTitle)){
					return Message.warn("发票抬头为空！");
				}
			}else {
				//专用发票
				if(StringUtil.isNullOrSpace(organizationName)){
					return Message.warn("发票单位名称为空！");
				}
				if(StringUtil.isNullOrSpace(registrationCode)){
					return Message.warn("发票纳税人识别码为空！");
				}
				if(StringUtil.isNullOrSpace(registerAddress)){
					return Message.warn("发票注册地址为空！");
				}
				if(StringUtil.isNullOrSpace(registerPhone)){
					return Message.warn("发票注册电话为空！");
				}
				if(StringUtil.isNullOrSpace(bankOfDeposit)){
					return Message.warn("发票开户银行为空！");
				}
				if(StringUtil.isNullOrSpace(bankAccount)){
					return Message.warn("发票银行账户为空！");
				}
				if(StringUtil.isNullOrSpace(consignee)){
					return Message.warn("发票收票人姓名为空！");
				}
				if(StringUtil.isNullOrSpace(phone)){
					return Message.warn("发票收票人电话为空！");
				}
				if(StringUtil.isNullOrSpace(address)){
					return Message.warn("发票收票人地址为空！");
				}
				invoice = new Invoice();
				invoice.setOrganizationName(organizationName);
				invoice.setRegistrationCode(registrationCode);
				invoice.setRegisterAddress(registerAddress);
				invoice.setRegisterPhone(registerPhone);
				invoice.setBankAccount(bankAccount);
				invoice.setBankOfDeposit(bankOfDeposit);
				invoice.setConsignee(consignee);
				invoice.setPhone(phone);
				invoice.setAddress(address);
			}
		}
		if(isInvoice && invoiceType == ParamsUtil.ORDER_INVOICE_TYPE_INCREMENT && invoice == null){
			return Message.warn("增值税发票信息填写不完整！");
		}
		Order order = orderService.create(shopId,orderType,cart, receiver, paymentMethod, shippingMethod, couponCode, isInvoice, invoiceTitle, useBalance, memo, null,schemeId,ids,schemeArea,invoice,invoiceType, isDissipate, isTemperature, isPromote, isController,jsonParam);
		return Message.success(order.getSn());
	}

	/**
	 * 支付
	 */
	@RequestMapping(value = "/payment", method = RequestMethod.GET)
	public String payment(String sn, ModelMap model) {
		Order order = orderService.findBySn(sn);
		if (order == null || !memberService.getCurrent().equals(order.getMember()) || order.isExpired() || order.getPaymentMethod() == null) {
			return ERROR_VIEW;
		}
		if (order.getPaymentMethod().getMethod() == PaymentMethod.Method.online) {
			List<PaymentPlugin> paymentPlugins = pluginService.getPaymentPlugins(true);
			if (!paymentPlugins.isEmpty()) {
				PaymentPlugin defaultPaymentPlugin = paymentPlugins.get(0);
				if (order.getPaymentStatus() == PaymentStatus.unpaid || order.getPaymentStatus() == PaymentStatus.partialPayment) {
					model.addAttribute("fee", defaultPaymentPlugin.calculateFee(order.getAmountPayable()));
					model.addAttribute("amount", defaultPaymentPlugin.calculateAmount(order.getAmountPayable()));
				}
				model.addAttribute("defaultPaymentPlugin", defaultPaymentPlugin);
				model.addAttribute("paymentPlugins", paymentPlugins);
			}
		}
		model.addAttribute("order", order);
		return "/shop/member/order/payment";
	}
	/**
	 * 支付
	 */
	@RequestMapping(value = "/tlpayment", method = RequestMethod.GET)
	public String tlpayment(String sn,String token,BigDecimal paymentAmount,HttpServletRequest request, ModelMap model) {
		Order order = orderService.findBySn(sn);
		Member member= memberService.getCurrent();
		PaymentDTO dto=new PaymentDTO();
		dto.setPayerName(member.getName());//名称
		dto.setPayerEmail(member.getEmail());//邮箱
		dto.setPayerTelephone(order.getPhone());//联系人电话
		if(order.getPaymentTimes()==null){
			order.setPaymentTimes(0);
		}else{
			order.setPaymentTimes(order.getPaymentTimes()+1);
		}
		dto.setOrderNo(order.getSn());//订单编号
		if(order.getOrderType()==ParamsUtil.CART_TYPE_SCHEME&&order.getSchemePaymentStatus()==ParamsUtil.SCHEME_PAYMENT_STATUS_PARTIALPAYMENT){
			dto.setOrderNo(order.getSn()+"-"+order.getPaymentTimes().toString());//订单编号
		}
		BigDecimal temp=paymentAmount==null?order.getAmount():paymentAmount;
		temp=temp.multiply(new BigDecimal("100"));
		temp=temp.setScale(0, BigDecimal.ROUND_HALF_UP); 
		dto.setOrderAmount(String.valueOf(temp));//应支付金额
		dto.setOrderDatetime(DateTime.timeToString(new Date()));//商户订单提交时间
		dto.setOrderExpireDatetime("5");//过期时间 order.getExpire()+""
		dto.setProductNum(String.valueOf(order.getQuantity()));
		dto.setProductDesc(order.getMemo());
		if(order.getOrderType()==ParamsUtil.CART_TYPE_NORMAL){
			dto.setProductName("766智能家商城单品订单");
			//常规商品
		}else{
			dto.setProductName("766智能家商城方案订单");
			//方案
		}
		PaymentUtil.getParams(dto,null);//028 6687983       15928898607 
		model.addAttribute("order",order);
		model.addAttribute("pay",dto);
		model.addAttribute("paymentAmount",paymentAmount);
		return "/shop/member/order/payment";
	}

	/**
	 * 计算支付金额
	 */
	@RequestMapping(value = "/calculate_amount", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> calculateAmount(String paymentPluginId, String sn) {
		Map<String, Object> data = new HashMap<String, Object>();
		Order order = orderService.findBySn(sn);
		PaymentPlugin paymentPlugin = pluginService.getPaymentPlugin(paymentPluginId);
		if (order == null || !memberService.getCurrent().equals(order.getMember()) || order.isExpired() || order.isLocked(null) || order.getPaymentMethod() == null || order.getPaymentMethod().getMethod() == PaymentMethod.Method.offline || paymentPlugin == null || !paymentPlugin.getIsEnabled()) {
			data.put("message", ERROR_MESSAGE);
			return data;
		}
		data.put("message", SUCCESS_MESSAGE);
		data.put("fee", paymentPlugin.calculateFee(order.getAmountPayable()));
		data.put("amount", paymentPlugin.calculateAmount(order.getAmountPayable()));
		return data;
	}

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Integer pageNumber, ModelMap model) {
		Member member = memberService.getCurrent();
		Pageable pageable = new Pageable(pageNumber, PAGE_SIZE);
		model.addAttribute("page", orderService.findPage(member, pageable));
		return "shop/member/order/list";
	}

	/**
	 * 查看
	 */
	@RequestMapping(value = "/view", method = RequestMethod.GET)
	public String view(String sn, ModelMap model) {
		Order order = orderService.findBySn(sn);
		if (order == null) {
			return ERROR_VIEW;
		}
		Member member = memberService.getCurrent();
		if (!member.getOrders().contains(order)) {
			return ERROR_VIEW;
		}
		model.addAttribute("order", order);
		return "shop/member/order/view";
	}

	
	@RequestMapping(value = "/cancelOrder", method = RequestMethod.GET)
	public @ResponseBody
	Message cancelOrder(String sn) {
		Order order = orderService.findBySn(sn);
		if (order != null && memberService.getCurrent().equals(order.getMember()) && !order.isExpired() && order.getOrderStatus() == OrderStatus.unconfirmed && order.getPaymentStatus() == PaymentStatus.unpaid) {
			if (order.isLocked(null)) {
				return Message.warn("shop.member.order.locked");
			}
			orderService.cancel(order, null);
			return SUCCESS_MESSAGE;
		}
		return ERROR_MESSAGE;
	}
	/**
	 * 取消
	 */
	@RequestMapping(value = "/cancel", method = RequestMethod.POST)
	public @ResponseBody
	Message cancel(String sn) {
		Order order = orderService.findBySn(sn);
		if (order != null && memberService.getCurrent().equals(order.getMember()) && !order.isExpired() && order.getOrderStatus() == OrderStatus.unconfirmed && order.getPaymentStatus() == PaymentStatus.unpaid) {
			if (order.isLocked(null)) {
				return Message.warn("shop.member.order.locked");
			}
			orderService.cancel(order, null);
			return SUCCESS_MESSAGE;
		}
		return ERROR_MESSAGE;
	}

	/**
	 * 物流动态
	 */
	@RequestMapping(value = "/delivery_query", method = RequestMethod.GET)
	public @ResponseBody
	Map<String, Object> deliveryQuery(String sn) {
		Map<String, Object> data = new HashMap<String, Object>();
		Shipping shipping = shippingService.findBySn(sn);
		Setting setting = SettingUtils.get();
		if (shipping != null && shipping.getOrder() != null && memberService.getCurrent().equals(shipping.getOrder().getMember()) && StringUtils.isNotEmpty(setting.getKuaidi100Key()) && StringUtils.isNotEmpty(shipping.getDeliveryCorpCode()) && StringUtils.isNotEmpty(shipping.getTrackingNo())) {
			data = shippingService.query(shipping);
		}
		return data;
	}
	
	@ResponseBody
	@RequestMapping(value="/searchArea")
	public String searcheArea(Long id){
		String str=null;
		if(null==id){
			List<Area> list= areaService.findRoots();
			str=JsonUtils.toJson(list);
		}else{
			List<AreaDto> list= areaService.findChildren(id);
			str=JsonUtils.toJson(list);
		}
		return str;
	}
	@ResponseBody
	@RequestMapping(value="/searchShop")
	public String searchShop(Long id){
		String str=null;
		if(null!=id){
			List<Shops> list= shopsService.getShopsByAreaId(id,false,null);
			str=JsonUtils.toJson(list);
		}
		return str;
	}
}